package client.setup;

import client.Identifier;
import constans.ConfigurationConstans;
import constans.SizeConstans;
import java.io.IOException;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import client.setup.gui.SetupFrame;
import utils.LogUtils;
import utils.MachineUtils;
import utils.ObjectUtils;


public class Setup {


    private static String arguments;

    
    public static void main(String args[]) {

       arguments = new String(args[0]);
                      
       java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

               Locale locale = getLocale(arguments);

               ResourceBundle resourceBundle = ResourceBundle.getBundle("client.setup.language/Language", locale);


               Logger logger = null;
               try {
                   logger = LogUtils.getLogger("rArcSetup", "rArcSetup.log");
               } catch (IOException e) {
                     reportAndExit( resourceBundle.getString("MessageTitleSetup"),resourceBundle.getString("MessageProblemsWriteDirectory"));
               }

               long freeSpace = (long) (MachineUtils.getFreeSpace(ConfigurationConstans.LOCAL_DIRECTORY)/SizeConstans.MByte);

               if(freeSpace < ConfigurationConstans.OFFER_SPACE_MIN){
                   reportAndExit( resourceBundle.getString("MessageTitleSetup"),resourceBundle.getString("MessageProblemsFreeSpace"));
               }
                
                try {

                    Identifier identifier = (Identifier) ObjectUtils.load(ConfigurationConstans.IDENTIFIER_FILENAME);

                    JOptionPane.showMessageDialog(null, resourceBundle.getString("MessageSetup"), resourceBundle.getString("MessageTitleSetup"), JOptionPane.INFORMATION_MESSAGE);
                    System.exit(0);

                } catch (IOException e) {
                    logger.log(Level.WARNING,"Problems("+e.getMessage()+")");
                } catch (ClassNotFoundException e) {
                    logger.log(Level.WARNING,"Problems("+e.getMessage()+")");
                }

            MachineUtils.deleteFile(ConfigurationConstans.LOCAL_DIRECTORY,
                        ConfigurationConstans.IDENTIFIER_FILENAME);

                new SetupFrame(resourceBundle, logger).setVisible(true);
            }
        });
    }


   private static void reportAndExit(String title, String error){
        JOptionPane.showMessageDialog(null, error, title, JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }



    private static Locale getLocale(String info){
        
        String language = info.substring(0,2);
        String country = info.substring(2,4);

        return new Locale(language,country);
    }


}
